<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */	

defined ('IN_AGORA') or die;

class TaskController extends AgoraAdminController
{
	function _default()
	{
		$sort_dir = Agora::getVar('filter_order_Dir','ASC');
		$sort_field = Agora::getVar('filter_order');

		$users_model = &Model::getInstance('UserModel');
		$users_model->sync();

		// sanity checks
		if (strcasecmp($sort_dir,'asc') != 0 && strcasecmp($sort_dir,'desc')) {
			$sort_dir = 'asc';
		}

		if (!in_array($sort_field,array('last_visit','num_posts','username','registered','email'))) {
			$sort_field = null;
		}

		if ($sort_field) {
			$users_model->setOrder('ORDER BY '.$sort_field.' '.$sort_dir);
		}


		$filter_strict = Agora::getVar('filter_strict',true);

		$filter = Agora::getVar('filter');
		if (!is_array($filter)) {
			$filter = array();
		}

		if (isset($filter['username'])) {
			if ($filter_strict) {
				$users_model->setFilter('username',$filter['username'], '=', 'j_u.');
			} else {
				$users_model->setFilter('username','%'.$filter['username'].'%','LIKE', 'j_u.');
			}
		} elseif (isset($filter['email'])) {
			if ($filter_strict) {
				$users_model->setFilter('email',$filter['email'], '=', 'j_u.');
			} else {
				$users_model->setFilter('email','%'.$filter['email'].'%','LIKE', 'j_u.');
			}
		}

		$this->setPagination($users_model->loadAllCount());
		$users = $users_model->loadAll('',$this->pagination->per_page,$this->pagination->page);

		$ban_model = &Model::getInstance('BanModel');
		foreach ($users as $id => $user) {
			$users[$id]['banned'] = $ban_model->isBanned($user['username']);
			$users[$id]['num_groups'] = $users_model->getGroupsCount($user['id']);
		}

		$this->view->assign('filter',$filter);
		$this->view->assign('filter_strict',$filter_strict);
		$this->view->assign('sort_dir',$sort_dir);
		$this->view->assign('sort_field',$sort_field);



		$group_model = & Model::getInstance('GroupModel');
		$groups = $group_model->loadAll();
		$groups = parseTree($groups,0,0,'id','parent_id', true);
		$this->view->assign('groups',$groups);
		$access_model = & Model::getInstance('AccessModel');
		$roles = array();
		foreach ($access_model->roles as $role_id => $role_name) {
			$roles[$role_id] = Agora::lang(str_replace('AGORA_ROLE_', '', $role_name));
		}
		$this->view->assign('roles', $roles);

		$this->view->assign('users',$users);
		$this->view->template = 'users/grouplist';
	}

	function filter()
	{
		$filter = Agora::getPostVar('filter');
		if (!$filter) {
			$filter = array();
		}

		$args = array();
		foreach ($filter as $f_name=>$f) {
			if ($f)
			$args[] = 'filter['.$f_name.']='.$f;
		}

		$strict = Agora::getPostVar('filter_strict',0);
		$args[] = 'filter_strict='.$strict;
		
		$users_model = &Model::getInstance('UserModel');
		$this->setPagination($users_model->loadAllCount());

		call_user_func_array(array($this,'redirect'), $args);
	}

	function sort()
	{
		$this->redirect('filter_order','filter_order_Dir');
	}

	function edit()
	{
		$cid = Agora::getPostVar('cid');
		if ($cid && is_array($cid)) {
			$user_id = array_shift($cid);
		} else {
			$user_id = Agora::getVar('user_id');
		}

		$user_model = &Model::getInstance('UserModel');
		$user = $user_model->load($user_id);

		if (!empty($user['birthday']) && $user['birthday'] !== '0') {
			$birthday = getdate($user['birthday']);


			$this->view->assign('birthday',array(
						'day'	=>	$birthday['mday'],
						'month'	=>	$birthday['mon'],
						'year'	=>	$birthday['year']
				));
		} else {
			$this->view->assign('birthday',array('day' => 0, 'month' => 0, 'year' => 0));
		}

		$groups = $user_model->getGroups($user['id']);
		$groups = parseTree($groups, 0, 0,'id','parent_id', true);
		$this->view->assign('groups',$groups);


		$warnings_model = &Model::getInstance('WarningModel');
		$warnings = $warnings_model->loadByUser($user_id);
		$this->view->assign('warnings',$warnings);

		$a_path = JPATH_ROOT . DS . $this->agora_config['o_avatars_dir'] .DS. $user['id'];

		if ($img_size = @getimagesize($a_path.'.gif'))
		//$avatar = Agora::getRoot().'img/pre_avatars/'.$post['user']['id'].'.gif';
		$avatar = JURI::root(). $this->agora_config['o_avatars_dir'] .'/'.$user['id'].'.gif';
		else if ($img_size = @getimagesize($a_path.'.jpg'))
		//$avatar = Agora::getRoot().'img/pre_avatars/'.$post['user']['id'].'.jpg';
		$avatar = JURI::root(). $this->agora_config['o_avatars_dir'] .'/'.$user['id'].'.jpg';
		else if ($img_size = @getimagesize($a_path.'.png'))
		//$avatar = Agora::getRoot().'img/pre_avatars/'.$post['user']['id'].'.png';
		$avatar = JURI::root(). $this->agora_config['o_avatars_dir'] .'/'.$user['id'].'.png';

		if (isset($avatar)) {
			$user['avatar'] = $avatar;
			$user['avatar_size'] = $img_size[3];
		} else {
			$user['avatar'] =Agora::getSite().'img/pre_avatars/noavatar.jpg';
			$user['avatar_size'] = '';
		}

		$this->view->assign('user',$user);
		$this->view->template = 'users/edit';
	}

	function add_warning()
	{
		$warnings_model = &Model::getInstance('WarningModel');
		$warnings = $warnings_model->loadAll();
		$filtered_warnings = array();
		$filtered_warnings_txt = array();
		$def_id=0;
		foreach ($warnings as $warning) {
		    if(!$def_id)
		    $def_id=$warning['id'];
		    
			$filtered_warnings[$warning['id']] = $warning['message'];
			$filtered_warnings_txt[$warning['id']] = $warning['message_txt'];
		}
		$this->view->assign('warnings',$filtered_warnings);
		$this->view->assign('warnings_txt',$filtered_warnings_txt);
		$this->view->assign('def_id',$def_id);

		$user_id = Agora::getVar('user_id');
		$this->view->assign('user_id',$user_id);
		$this->view->template = 'users/add_warning';
	}

	function delete_warnings()
	{
		$cid = Agora::getPostVar('cid_w');

		$warnings_model = &Model::getInstance('WarningModel');
		foreach ($cid as $id) {
			$warnings_model->deleteFromUser($id);
		}
		$this->redirect('action=edit','user_id');

	}

	function save_warning()
	{
		$form = Agora::getPostVar('form');
		$user_id = $form['user_id'];
        $warnings_model = &Model::getInstance('WarningModel');
		$warnings_model->addToUser($user_id, $form['warning_id'],$form['message']);		
		$wrng = $warnings_model->load($form['warning_id']);
		$user_model = &Model::getInstance('UserModel');
		$user = $user_model->load($user_id);
		
                $mail = JFactory::getMailer();
                $mail->addRecipient( $user['email']);
                $mail->setSubject("You get " .$wrng["points"]. "warning points. " .$wrng["message"]);
                $mail->setBody( $form['message'] );
                $mail->IsHTML(true);
                $mail->Send();
                
        $u_warnings = $warnings_model->loadByUser($user_id);
        $total_points=0;
        foreach ($u_warnings as $u_warning)
        {
            if ( time() < $u_warning["expire"])
            {
                $total_points += $u_warning["points"];
            }
        }
        
        $autoban_model = & Model::getInstance('AutobanModel');
        $autoban_model->setOrder('ORDER BY points DESC');
		$autobans = $autoban_model->loadAll();
		foreach ($autobans as $autoban)
		{
		    if ($autoban["points"] <= $total_points)
		    {
		        $ban_add["username"] = $user["username"];
		        $ban_add["message"] = $autoban["message"];
		        $ban_add["expire"] = time() + $autoban["expire"];
		        $ban_add["ip"]='';
		        $ban_add["email"]='';		        
		        $ban_model = & Model::getInstance('BanModel');
		        $ban_model->add($ban_add);
		        
		        unset($mail);
                $mail = JFactory::getMailer();
                $mail->addRecipient( $user['email']);
                $mail->setSubject("You banned for " .$total_points. "unexpired warning points. " .$autoban["message"]);
                $mail->setBody( $autoban["message_txt"] );
                $mail->IsHTML(true);
                $mail->Send();
		        
		        break;
		    }
		}
        
		
		$this->redirect('action=edit','user_id='.$user_id);
	}

	function next_role()
	{
		$group_id = Agora::getVar('group_id');
		$user_id = Agora::getVar('user_id');
		$access_model = &Model::getInstance('AccessModel');
		$role = $access_model->getRole($user_id, $group_id);
		if ($role >= 4) {
			$role = 1;
		} else {
			$role = $role + 1;
		}
		$access_model->setRole($user_id,$group_id,$role);
		$this->redirect('action=edit','user_id');
	}
	
	function mass_add_group() {
		$form = Agora::getPostVar('form');
		$group_model =& Model::getInstance('GroupModel');

		$users_model =& Model::getInstance('UserModel');
		$cid = Agora::getPostVar('cid',array());
		
		foreach ($cid as $uid) {
			
			if ($form['group_id'] > 0) {

				if ($parent = $group_model->getParent($form['group_id'])) {
				
					$grps = $users_model->getGroups($uid);
					$user_groups = array();
					
					foreach ($grps as $key => $grp) {
						$user_groups[] = $grp['id'];
					}

					if (!in_array($parent,$user_groups)) {
						JError::raiseWarning( 0, JText::_('Sorry you need to select the Parent group First. The Chicken REALLY did come before the egg') );
						$this->redirect('action=edit','user_id');
					}
				}
				$group_model->addUser($form['group_id'],$uid,$form['role_id']);

			} else {
				JError::raiseNotice( 0, JText::_('NO CHANGES MADE') );
			}
		}

		$this->redirect('task=usergroups');
		
		
	}
	
	function add_group()
	{
		$user_id = Agora::getVar('user_id');

		$user_model = & Model::getInstance('UserModel');
		$user_groups = $user_model->getGroups($user_id);

		$group_model = & Model::getInstance('GroupModel');

		$groups = $group_model->loadAll();

		foreach ($groups as $grp_key => $group) {
			foreach ($user_groups as $user_group) {
				if ($group['id'] == $user_group['id']) {
					// Temp work around.
					// Unsetting hides the group in the Add Group window
					// Selecting a Group which is already added has no ill effects

					//unset($groups[$grp_key]);

					$groups[$grp_key]['name'] = $groups[$grp_key]['name'] . ' *';
				}
			}
		}

		$groups = parseTree($groups,0,0,'id','parent_id', true);
		$this->view->assign('groups',$groups);

		$access_model = & Model::getInstance('AccessModel');
		$this->view->assign('roles',$access_model->roles);

		$this->view->assign('user_id',$user_id);
		$this->view->template = 'users/group';
	}

	function save_group()
	{
		$form = Agora::getPostVar('form');
		$group_model =&Model::getInstance('GroupModel');
		/* if (!isset($form['group_id'])) {
			Agora::showError('Please select group to add');
			$this->add_group();
			return;
		} */
		if($form['group_id'] > 0)
		{
			$users_model = & Model::getInstance('UserModel');

			if ($parent = $group_model->getParent($form['group_id']))
			{
				$grps = $users_model->getGroups($form['user_id']);
				$user_groups = array();
				foreach ($grps as $key => $grp)
				{
					$user_groups[] = $grp['id'];
				}

				if (!in_array($parent,$user_groups))
				{
					JError::raiseWarning( 0, JText::_('Sorry you need to select the Parent group First. The Chicken REALLY did come before the egg') );
					$this->redirect('action=edit','user_id');
				}
			} // end if has parent

			$group_model->addUser($form['group_id'],$form['user_id'],$form['role_id']);

		} // end  good id
		else
		{
			JError::raiseNotice( 0, JText::_('NO CHANGES MADE') );
		}


		$this->redirect('action=edit','user_id');
	}

	function delete_groups()
	{
		$form = Agora::getPostVar('form',array());
		$cid = Agora::getPostVar('cid',array());
		$user_id = $form['user_id'];
		$group_model = & Model::getInstance('GroupModel');
		$group_model = & Model::getInstance('GroupModel');
		$user_model = & Model::getInstance('UserModel');

		foreach ($cid as $group_id) {

			if ($children = $group_model->getChildren($group_id))
			{
				$grps = $user_model->getGroups($user_id);
				$usergroups = array();
				foreach ($grps as $key => $grp)
				{
					$usergroups[] = $grp['id'];
				}
				if (array_intersect($children,$usergroups))
				{
					JError::raiseWarning( 0, JText::_('Sorry, you need to remove all Child Groups first!') );
					$this->redirect('action=edit','user_id='.$user_id);
				}
				else
				{
					$group_model->removeUser($group_id,$user_id);
				}
			}
			else
			{
				$group_model->removeUser($group_id,$user_id);
			}
		}
		$this->redirect('action=edit','user_id='.$user_id);
	}

	function _remove_avatar($user_id)
	{
		$f_name = JPATH_ROOT . DS . $this->agora_config['o_avatars_dir'] .DS.$user_id;

		@unlink($f_name.'.gif');
		@unlink($f_name.'.jpg');
		@unlink($f_name.'.png');
	}
	
	function _save_avatar($user_id)
	{
		$uploaded_file = $_FILES['avatar'];

		if (!is_uploaded_file($uploaded_file['tmp_name'])) {
			Agora::showError(Agora::lang('Upload error'));
			return FALSE;
		}

		$allowed_types = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');

		if (!in_array($uploaded_file['type'], $allowed_types)) {
			Agora::showError(Agora::lang('Only images are allowed'));
			return FALSE;
		}

		if ($uploaded_file['size'] > $this->agora_config['o_avatars_size']) {
			Agora::showError(Agora::lang('Avatar is too large. Maximum allowed').' '.$this->agora_config['o_avatars_size']);
			$this->redirect('action');
		}

		$ext = null;
		if ($uploaded_file['type'] == 'image/gif')
			$ext = '.gif';
		elseif ($uploaded_file['type'] == 'image/jpeg' || $uploaded_file['type'] == 'image/pjpeg')
			$ext = '.jpg';
		else
			$ext = '.png';

		//$src_file = AGORA_PATH.'img'.DS.'pre_avatars'.DS.$this->user_id.'.tmp';
		$src_file = JPATH_ROOT . DS . $this->agora_config['o_avatars_dir'] .DS.$user_id.'.tmp';
		// Move the file to the avatar directory. We do this before checking the width/height to circumvent open_basedir restrictions.
		if (!@move_uploaded_file($uploaded_file['tmp_name'], $src_file)) {
			Agora::showError(Agora::lang('Cannot move uploaded file. Bad permissions'));
			return FALSE;
		}

		list($width, $height, $type,) = getimagesize($src_file);
		if (empty($width) ||
			empty($height) ||
			$width > $this->agora_config['o_avatars_width'] ||
			$height > $this->agora_config['o_avatars_height'])
		{
			@unlink($src_file);
			Agora::showError(Agora::lang('Avatar is too large. Maximum allowed').' '.$this->agora_config['o_avatars_width'].'x'.$this->agora_config['o_avatars_height']);
			return FALSE;
		}
		elseif ($type == 1 && $uploaded_file['type'] != 'image/gif')	// Prevent dodgy uploads
		{
			@unlink($src_file);
			Agora::showError(Agora::lang('Upload error (dodgy upload)'));
			return FALSE;
		}

		//$dest_file = AGORA_PATH.DS.'img'.DS.'pre_avatars'.DS.$this->user_id;
		$dest_file = JPATH_ROOT . DS . $this->agora_config['o_avatars_dir'] .DS.$user_id;

		@unlink($dest_file.'.gif');
		@unlink($dest_file.'.png');
		@unlink($dest_file.'.jpg');
		@rename($src_file, $dest_file.$ext);

		@chmod($dest_file.'.'.$ext, 0644);

		return TRUE;
	}

	function save()
	{
		$form = Agora::getPostVar('form',array());
		$user_id = $form['user_id'];

		if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == UPLOAD_ERR_OK) {
			if (!$this->_save_avatar($user_id)) {
				$this->redirect('action=edit','user_id='.$user_id);
			}
			$form['use_avatar'] = '1';
		} elseif ($form['remove_avatar']) {
			$this->_remove_avatar($user_id);
			$form['use_avatar'] = '0';
		}

		unset($form['user_id']);
		unset($form['remove_avatar']);

		if (checkdate(
				$form['birthday-month'],
				$form['birthday-day'],
				$form['birthday-year'])) {

			$form['birthday'] = mktime(0,0,0, $form['birthday-month'], $form['birthday-day'], $form['birthday-year']);
		} else {
			$form['birthday'] = 0;
		}
		unset($form['birthday-month']);
		unset($form['birthday-year']);
		unset($form['birthday-day']);

		$user_model = & Model::getInstance('UserModel');
		$user_model->edit($user_id,$form);
		$this->redirect();
	}

}
?>
